package com.meida.module.bus.provider.service.impl;

import com.google.common.collect.Lists;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaDelete;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.admin.client.entity.BaseUser;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.bus.client.entity.BusDept;
import com.meida.module.bus.client.entity.BusProject;
import com.meida.module.bus.client.entity.BusUserDept;
import com.meida.module.bus.provider.mapper.BusDeptMapper;
import com.meida.module.bus.provider.service.BusDeptService;
import com.meida.module.bus.provider.service.BusProjectService;
import com.meida.module.bus.provider.service.BusUserDeptService;
import com.meida.module.bus.provider.utils.MyFlymeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门接口实现类
 *
 * @author flyme
 * @date 2020-12-16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusDeptServiceImpl extends BaseServiceImpl<BusDeptMapper, BusDept> implements BusDeptService {
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BusUserDeptService busUserDeptService;
    @Autowired
    private BusProjectService busProjectService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusDept dept, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusDept> cq, BusDept dept, EntityMap requestMap) {
        cq.orderByDesc("dept.createTime");
        return ResultBody.ok();
    }

    @Override
    public void saveUserDepts(Long userId, String... deptIds) {
        if (userId == null || deptIds == null) {
            return;
        }
        BaseUser user = baseUserService.getUserById(userId);
        if (user == null) {
            return;
        }
        // 先清空,在添加
        removeUserDepts(userId);
        if (deptIds.length > 0) {
            for (String deptId : deptIds) {
                BusUserDept busUserDept = new BusUserDept();
                busUserDept.setUserId(userId);
                busUserDept.setDeptId(Long.parseLong(deptId));
                busUserDeptService.save(busUserDept);
            }
            List<String> deptIdList = Arrays.asList(deptIds);
            Collection<BusDept> busDeptList = listByIds(deptIdList);
            List<String> deptCodesList = busDeptList.stream().map(BusDept::getDeptCode).collect(Collectors.toList());
            String redisKey = "userDeptCodes_" + userId;
            String deptCodesStr = FlymeUtils.listToString(deptCodesList, ',');
            redisUtils.set(redisKey, deptCodesStr);

        }


    }

    @Override
    public void removeUserDepts(Long userId) {
        CriteriaDelete cd = new CriteriaDelete();
        cd.eq("userId", userId);
        busUserDeptService.remove(cd);
    }

    @Override
    public List<String> getUserDepts(Long userId) {
        List<String> deptCodesList = Lists.newArrayList();
        String redisKey = "userDeptCodes_" + userId;
        if (redisUtils.hasKey(redisKey)) {
            String deptCodesStr = (String) redisUtils.get(redisKey);
            deptCodesList = MyFlymeUtils.stringToList(deptCodesStr);
        } else {
            CriteriaQuery<BusUserDept> cq = new CriteriaQuery(BusUserDept.class);
            cq.select("deptCode");
            cq.eq("userId", userId);
            cq.createJoin(BusDept.class).setMainField("deptId").setJoinField("deptId");
            List<EntityMap> entityMapList = selectEntityMap(cq);
            deptCodesList = entityMapList.stream().map(entityMap -> entityMap.get("deptCode").toString()).collect(Collectors.toList());
            String deptCodesStr = FlymeUtils.listToString(deptCodesList, ',');
            redisUtils.set(redisKey, deptCodesStr);
        }
        return deptCodesList;
    }

    @Override
    public ResultBody getAllDeptProject() {
        List<EntityMap> deptList = getAllDept();
        List<BusProject> busProjectList = busProjectService.list();
        for (EntityMap entityMap : deptList) {
            String deptCode = entityMap.get("deptCode");
            List<EntityMap> projectList = new ArrayList<>();
            for (BusProject busProject : busProjectList) {
                String goodsPurGroupCode = busProject.getGoodsPurGroupCode();
                if (deptCode.equals(goodsPurGroupCode)) {
                    EntityMap entityMap1 = new EntityMap();
                    entityMap1.put("id", busProject.getProjectId());
                    entityMap1.put("name", busProject.getProjectName());
                    projectList.add(entityMap1);
                }
            }
            entityMap.put("children", projectList);
        }
        return ResultBody.ok(deptList);
    }

    @Override
    public List<EntityMap> getAllDept() {
        CriteriaQuery<BusDept> cq = new CriteriaQuery(BusDept.class);
        cq.select("deptId as id,deptName as name,deptCode");
        return selectEntityMap(cq);
    }
}
